package com.corot.codoc.service.impl;

import com.corot.codoc.bean.EBook;
import com.corot.codoc.bean.Segment;
import com.corot.codoc.dao.EBookDao;
import com.corot.codoc.dao.SegmentDao;
import com.corot.codoc.exception.DataException;
import com.corot.codoc.exception.ParamException;
import com.corot.codoc.service.SegmentService;
import com.corot.core.model.entity.BaseEntity;
import com.corot.core.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.Set;

/**
 * 类的描述
 *
 * @author leesir
 */
@Service
@Transactional
public class SegmentServiceImpl implements SegmentService {

    @Autowired
    private SegmentDao segmentDao;

    @Autowired
    private EBookDao eBookDao;

    @Override
    public void createSegment(String name, Integer parentId, Integer eBookId) throws InvocationTargetException, IllegalAccessException {
        if(valid(name,parentId,eBookId)){
            Segment segment = new Segment();
            if(parentId!=null){
                Segment parent = segmentDao.get(parentId);
                segment.setParent(parent);
            }else {
                EBook eBook = eBookDao.get(eBookId);
                segment.seteBook(eBook);
            }
            segment.setName(name);
            segmentDao.save(segment);
        }
    }

    private boolean valid(String name, Integer parentId, Integer eBookId) {
        if(StringUtils.isBlank(name)){
            throw new ParamException("章节的名字不能为空");
        } else if(parentId==null&&eBookId==null){
            throw new ParamException("不能既没有父章节也没有指定电子书");
        }else if(parentId!=null){
            Segment segment = segmentDao.get(parentId);
            if(segment==null|| BaseEntity.DEL_FLAG_DELETE.equals(segment.getDelFlag())){
                throw new DataException("父章节无效");
            }
        }else {
            EBook eBook = eBookDao.get(eBookId);
            if(eBook==null||BaseEntity.DEL_FLAG_DELETE.equals(eBook.getDelFlag())){
                throw new DataException("电子书无效");
            }
        }
        return true;
    }

    @Override
    public void updateSegment(Segment segment) throws InvocationTargetException, IllegalAccessException {
        segmentDao.save(segment);
    }

    @Override
    public void deleteSegment(Integer id) {
        segmentDao.deleteById(id);
    }

    @Override
    public Set<Segment> getSegments(Integer eBookId) {
        //TODO 还没开写
        return null;
    }
}
